'''
Author: lijiantao
Date: 2023-09-12 19:54:54
LastEditors: lijiantao
LastEditTime: 2023-10-13 20:26:46
FilePath: \mov2pic\mov2pic.py
Description: 
lijiantao@mail.ustc.edu.cn
Copyright (c) 2023 by lijiantao/ustc, All Rights Reserved. 
'''
import ffmpeg
import cv2


import os


def mov2pic():
    # 指定目录路径
    directory_path = 'mov/'

    # 使用os模块的listdir方法列出目录下的所有文件和子目录
    files_and_directories = os.listdir(directory_path)

    # 过滤出目录下的文件
    files = [f for f in files_and_directories if os.path.isfile(os.path.join(directory_path, f))]

    # 打印所有文件的名称
    for filename in files:
        print('处理'+filename+'中...')
        # 保存帧的目录
        output_directory = 'pic/'


        # 打开视频文件
        # input_stream = ffmpeg.input(directory_path+filename)
        # os.makedirs(output_directory+filename[:-4], exist_ok=True)
        # # 生成帧图片
        # (
        #     ffmpeg
        #     .output(input_stream, output_directory+filename[:-4]+'/frame_%07d.png')  # 图片文件名的格式，%04d 表示四位数字，可根据需要更改
        #     .run()
        # )
        # # 打开视频文件
        cap = cv2.VideoCapture(directory_path+filename)

        # 确保视频文件打开成功
        if not cap.isOpened():
            print("错误: 不能打开视频。")
            exit()

        os.makedirs(output_directory+filename[:-4], exist_ok=True)

        frame_count = 0

        while True:
            # 读取一帧
            ret, frame = cap.read()

            # 如果没有更多帧可读，则退出循环
            if not ret:
                print('没有更多帧可读。')
                break

            # 构造保存帧的文件名
            frame_filename = os.path.join(output_directory+filename[0:-4], f'frame_{frame_count:07d}.jpg')
            # print(frame_filename)
            # 保存帧为图片
            cv2.imencode('.jpg',frame)[1].tofile(frame_filename)

            # cv2.imwrite(frame_filename, frame)

            frame_count += 1
            print("第"+str(frame_count)+"帧")

        # 释放视频文件
        cap.release()

        print(f" 保存了 {frame_count}帧到 {output_directory+filename[:-4]}中。")

if __name__ == '__main__':
    mov2pic()




